﻿using Iot.Models;

namespace Iot.Middleware
{
    public class StatusServiceMiddleware
    {
        private readonly IClientWorker? _clientWorker;
        private readonly RequestDelegate _next;
        public StatusServiceMiddleware(RequestDelegate next, IClientWorker? clientWorker)
        {
            _next = next;
            _clientWorker = clientWorker;
        }

        /// <summary>
        /// 向所有设备发送状态更新指令
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            var switchs = AppData.AppConfig.Switchs;
            foreach (var item in switchs)
            {
                // 向设备发送更新状态指令
                if (_clientWorker != null )
                    await _clientWorker.PublishAsync(MQTTTOPIC.CONTROL, new MQTTMessage() { Msg = "2", To = item.DeviceMAC, GPIO = item.GPIO });
            }
            await _next.Invoke(context);
        }
    }

    public static class StatusServiceExt {
        public static IApplicationBuilder UseStatusService(this IApplicationBuilder app)
        {
            return app.UseMiddleware<StatusServiceMiddleware>();
        }
    }
}
